package com.yzy.mall.component

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SpanUtils
import com.yzy.baselibrary.extention.*
import com.yzy.mall.R
import com.yzy.mall.component.comm.CommActivity
import com.yzy.mall.repository.*
import com.yzy.mall.utils.AssetsUtils
import kotlinx.android.synthetic.main.activity_exchange.*
import java.math.BigDecimal


class ExchangeActivity : CommActivity() {
    companion object {
        fun startExchangeActivity(context: Context, userListBean: CardBean) {
            context.startActivity<ExchangeActivity>(
                "userOrderBean" to userListBean
            )
        }
    }

    var saveBean: SaveBean? = null
    private val mViewModel: SaveViewModel by lazy {
        ViewModelProvider(
            this,
            ViewModelFactory()
        ).get(SaveViewModel::class.java)
    }

    override fun layoutResId(): Int = R.layout.activity_exchange

    override fun initView() {
        tvUserNameTitle.text =
            SpanUtils().append("姓名").setForegroundColor(Color.parseColor("#000000")).append("*")
                .setForegroundColor(Color.parseColor("#C71212")).create()
        tvUserPhoneTitle.text =
            SpanUtils().append("您的手机号码").setForegroundColor(Color.parseColor("#000000")).append("*")
                .setForegroundColor(Color.parseColor("#C71212")).create()
        tvProvinceTitle.text =
            SpanUtils().append("省").setForegroundColor(Color.parseColor("#000000")).append("*")
                .setForegroundColor(Color.parseColor("#C71212")).create()
        tvCityTitle.text =
            SpanUtils().append("城市").setForegroundColor(Color.parseColor("#000000")).append("*")
                .setForegroundColor(Color.parseColor("#C71212")).create()
        tvAreaTitle.text =
            SpanUtils().append("区").setForegroundColor(Color.parseColor("#000000")).append("*")
                .setForegroundColor(Color.parseColor("#C71212")).create()
        tvFixedPhoneTitle.text =
            SpanUtils().append("固定电话").setForegroundColor(Color.parseColor("#000000"))
                .append("（电话格式：021-xxxxxxx）").setForegroundColor(Color.parseColor("#aaaaaa"))
                .create()
        tvDetailedTitle.text =
            SpanUtils().append("详细地址").setForegroundColor(Color.parseColor("#000000")).append("*")
                .setForegroundColor(Color.parseColor("#C71212")).create()

        rvWheel1.layoutManager = LinearLayoutManager(mContext)
        rvWheel2.layoutManager = LinearLayoutManager(mContext)
        rvWheel3.layoutManager = LinearLayoutManager(mContext)
        provinceAdapter = ProvinceAdapter()
        cityAdapter = CityAdapter()
        areaAdapter = AreaAdapter()
        rvWheel1.adapter = provinceAdapter
        rvWheel2.adapter = cityAdapter
        rvWheel3.adapter = areaAdapter
        provinceAdapter.setOnItemClickListener { adapter, view, position ->
            val provinceBean = provinceAdapter.data[position]
            tvProvince.text = provinceBean.name
            cityAdapter.setList(provinceBean.city)
            rvWheel1.gone()
        }

        cityAdapter.setOnItemClickListener { adapter, view, position ->
            val provinceBean = cityAdapter.data[position]
            tvCity.text = provinceBean.name
            areaAdapter.setList(provinceBean.area)
            rvWheel2.gone()
        }

        areaAdapter.setOnItemClickListener { adapter, view, position ->
            val str = areaAdapter.data[position]
            tvArea.text = str
            rvWheel3.gone()
        }
        tvLeft.click {
            finish()
        }
        provinceAdapter.setList(AssetsUtils.instance.getProvinceBean())
        tvSaveSubmit.click {
            KeyboardUtils.hideSoftInput(this)
            val userName = tvEditUserName.text.trim().toString()
            if (userName.isEmpty()) {
                toast("请填写收货人姓名！")
                return@click
            }

            val userPhone = tvEditUserPhone.text.trim().toString()
            if (userPhone.isEmpty()) {
                toast("请填写收货人电话号码！")
                return@click
            }

            if (!RegexUtils.isMobileExact(userPhone)) {
                toast("请填写正确电话号码！")
                return@click
            }
            if (tvProvince.text.toString() == "省份/直辖市" || tvCity.text.toString() == "市" || tvArea.text.toString() == "县/区") {
                toast("请选择地址！")
                return@click
            }

            val userDetailed = tvDetailedTitle.text.trim().toString()
            if (userDetailed.isEmpty()) {
                toast("请填写详细地址！")
                return@click
            }

            tvEditUserName.isFocusable = false;//不可编辑
            tvEditUserName.isFocusableInTouchMode = false;//不可编辑

            tvDetailedTitle.isFocusable = false;//不可编辑
            tvDetailedTitle.isFocusableInTouchMode = false;//不可编辑

            tvEditUserPhone.isFocusable = false;//不可编辑
            tvEditUserPhone.isFocusableInTouchMode = false;//不可编辑

            clBottomVIew.visible()
            llSubmitView.gone()
        }
        tvClose.click {
            finish()
        }
        linearLayout.click {
            if (!gQrCodeBg.isVisible) {
                gQrCodeBg.visible()
                return@click
            }
            tvQrSuccess.gone()
            gQrCodeBg.visible()
            ivCashSelect.setImageResource(R.drawable.icon_no_select)
            ivQrSelectView.setImageResource(R.drawable.icon_select)
        }

        llCash.click {
            if (!tvQrSuccess.isVisible) {
                tvQrSuccess.visible()
                return@click
            }
            gQrCodeBg.gone()
            tvSaveSuccess.visible()
            ivQrSelectView.setImageResource(R.drawable.icon_no_select)
            ivCashSelect.setImageResource(R.drawable.icon_select)
        }
        tvSaveSuccess.click {
            memberInfo?.let { bean ->
                val userPhone = tvEditUserPhone.text.trim().toString()
                val userName = tvEditUserName.text.trim().toString()
                val buyWineName = vBean?.buy_wine_name ?: ""
                val buy_points = vBean?.single_integral ?:0
                val province = tvProvince.text.toString()
                val city = tvCity.text.toString()
                val area = tvArea.text.toString()
                val fixedPhone = tvFixedPhone.text.toString()
                val postcode = tvPostcode.text.toString()
                val moneyCount = tvMoneyCount.text.toString().replace("¥", "")
                val countCommodityFreightMoney =tvCountCommodityFreightMoney.text.toString().replace("¥", "")
                val discountMoney = tvDiscountMoney.text.toString().replace("¥", "")
                val count = tvCount.text.toString()
                val detailed = etDetailed.text.toString()
                val receivingAddress = province + city + area + detailed
                saveBean = SaveBean(
                    idCard = bean.idCard,
                    phoneNo = userPhone,
                    userName = userName,
                    exchangeWineName = buyWineName,
                    provinceName = province,
                    cityName = city,
                    districtName = area,
                    fixedTelephone = fixedPhone,
                    detailAddress = detailed,
                    zipCode = postcode,
                    payMethod = "现金支付",
                    commodityTotalPrice = moneyCount,
                    preferentialAmount = discountMoney,
                    commodityFreight = countCommodityFreightMoney,
                    exchangeNum = count,
                    receivingAddress = receivingAddress,
                    singlePoint=buy_points.toString(),
                    exchangePoint = (buy_points *  (count.toInt())).toString()
                )
                saveBean?.let {
                    mViewModel.exchangeInfo(it)
                }
            }
        }
        mViewModel.uiState.observe(this, Observer {
            val showLoading = it?.showLoading ?: false
            if (showLoading) {
                showLoadingView()
            } else {
                dismissLoadingView()
            }

            it?.success?.let { success ->
                var s = success as Boolean
                if (s) {
                    saveBean?.let { bean ->
                        OrderSuccessActivity.startOrderSuccessActivity(mContext, bean)
                        finish()
                    }
                } else {
                    toast("订单提交失败")
                }
            }
        })
    }

    var vBean: ViolationRecord? = null
    var numberCount: Int = 1
    var count: Int = 0
    var memberInfo: MemberInfo? = null
    lateinit var orderAdapter: OrderAdapter
    lateinit var provinceAdapter: ProvinceAdapter
    lateinit var cityAdapter: CityAdapter
    lateinit var areaAdapter: AreaAdapter
    override fun initData() {
        tvProvince.click {
            KeyboardUtils.hideSoftInput(this)
            val location = IntArray(2)
            tvProvince.getLocationOnScreen(location)
            rvWheel1.x = location[0].toFloat()
            rvWheel1.y = (location[1] + tvProvince.height).toFloat()
            rvWheel1.visible()
            llOrderListView.gone()
            rvWheel2.gone()
            rvWheel3.gone()
            tvCity.text = "市"
            tvArea.text = "县/区"
        }

        tvCity.click {
            KeyboardUtils.hideSoftInput(this)
            if (tvProvince.text.toString() == "省份/直辖市") {
                tvProvince.performClick()
            } else {
                val location = IntArray(2)
                tvCity.getLocationOnScreen(location)
                rvWheel2.x = location[0].toFloat()
                rvWheel2.y = (location[1] + tvCity.height).toFloat()
                rvWheel2.visible()
                llOrderListView.gone()
                rvWheel1.gone()
                rvWheel3.gone()
                tvArea.text = "县/区"
            }
        }

        tvArea.click {
            KeyboardUtils.hideSoftInput(this)
            if (tvCity.text.toString() == "市") {
                tvCity.performClick()
            } else {
                val location = IntArray(2)
                tvArea.getLocationOnScreen(location)
                rvWheel3.x = location[0].toFloat()
                rvWheel3.y = (location[1] + tvArea.height).toFloat()
                rvWheel3.visible()
                llOrderListView.gone()
                rvWheel1.gone()
                rvWheel2.gone()
            }

        }

        val userListBean = intent.getParcelableExtra<CardBean>("userOrderBean")
        llOrderListView.layoutManager = LinearLayoutManager(mContext)
        orderAdapter = OrderAdapter()
        llOrderListView.adapter = orderAdapter
        userListBean?.let {
            val violationRecord = userListBean.violation_record
            memberInfo = userListBean.memberInfo
            violationRecord?.let { violationBean ->
                if (violationBean.size > 0) {
                    orderAdapter.setList(violationBean)
                    setShowView(violationBean[0])
                }
            }
            orderAdapter.setOnItemClickListener { adapter, view, position ->
                setShowView(orderAdapter.data[position])
                llOrderListView.gone()
            }
        }

        ivNumberAdd.click {
            val txetCount = tvCount.text.toString().toInt()
            val maxCount = txetCount + 1
            if (maxCount <= numberCount && maxCount<= count){
                tvCount.text = maxCount.toString()
            }
            setMoneyUi()
        }
        imageView.click {
            val textCount = tvCount.text.toString().toInt()
            val minCount = textCount - 1
            if (minCount < 1){
                return@click
            }
            tvCount.text = minCount.toString()
            setMoneyUi()
        }
        tvExchangeTypeName.click {
            KeyboardUtils.hideSoftInput(this)
            val location = IntArray(2)
            tvExchangeTypeName.getLocationOnScreen(location)
            llOrderListView.x = location[0].toFloat()
            llOrderListView.y = (location[1] + tvExchangeTypeName.height).toFloat()
            llOrderListView.visible()
            rvWheel1.gone()
            rvWheel2.gone()
            rvWheel3.gone()
        }
    }


    @SuppressLint("SetTextI18n")
    private fun setShowView(bean: ViolationRecord) {
        tvExchangeTypeName.text = bean.buy_wine_name
        tvCount.text = "1"
        count=bean.buy_number?:0
        imageView.isClickable = false
//        val residualPoints = 80000
        memberInfo?.let { info ->
            LogUtils.e((info.residualPoints ?: 0))
            LogUtils.e( (bean?.buy_points ?: 0))
            val toString = ((info.residualPoints ?: 0) / (bean.single_integral ?: 0)).toString()
//            val toString = (residualPoints / (bean.buy_points ?: 0)).toString()
            numberCount = BigDecimal(toString).setScale(BigDecimal.ROUND_DOWN).intValueExact()
//            tvSaveCount.text = "（当前积分最多可兑换${numberCount}瓶）"
            tvSaveCount.text = "（当前积分最多可兑换${numberCount}瓶限购${bean.buy_number}瓶）"
        }
        tvCountCommodityFreightMoney.text = "¥${bean.commodity_freight}"
        vBean = bean
        setMoneyUi()
    }

    @SuppressLint("SetTextI18n")
    fun setMoneyUi() {
        val numberCount = tvCount.text.toString().toInt()
        val isYouHuiMoney = if ((vBean?.preferential_amount ?: 0.0) <= 0.0) (vBean?.wine_price
            ?: 0.0) else (vBean?.preferential_amount ?: 0.0)
        val moneyCont =
            BigDecimal((isYouHuiMoney * numberCount).toString()).setScale(2, BigDecimal.ROUND_DOWN)
                .toString()
        tvMoneyCount.text = "¥${moneyCont}"
        tvCountCommodityMoney.text = "¥${moneyCont}"
        val countCommodityMoney =
            if ((vBean?.preferential_amount ?: 0.0) <= 0.0) 0.0 else ((vBean?.wine_price
                ?: 0.0) * numberCount) - ((vBean?.preferential_amount ?: 0.0) * numberCount)
        tvDiscountMoney.text =
            "¥${BigDecimal(countCommodityMoney.toString()).setScale(2, BigDecimal.ROUND_DOWN)}"
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if ((ev.action and MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
            //点击位置是否是底部是"操作面板+内容面板"部分
            val rvWheel11 = isTouchPointInSendLayout(rvWheel1, ev)
            val rvWheel22 = isTouchPointInSendLayout(rvWheel2, ev)
            val rvWheel33 = isTouchPointInSendLayout(rvWheel3, ev)
            val llOrderListView1 = isTouchPointInSendLayout(llOrderListView, ev)
            //点击【非】"操作面板+内容面板"部分需要关闭键盘或"内容面板"
            if (rvWheel1.isVisible && !rvWheel11) {
                rvWheel1.gone()
            }
            if (rvWheel2.isVisible && !rvWheel22) {
                rvWheel2.gone()
            }
            if (rvWheel3.isVisible && !rvWheel33) {
                rvWheel3.gone()
            }

            if (llOrderListView.isVisible && !llOrderListView1) {
                llOrderListView.gone()
            }
            val v = currentFocus
            if (isShouldHideInput(v, ev)) {
                v?.let {v1->
                    (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(v1.windowToken, 0)
                }

            }
        }

        return super.dispatchTouchEvent(ev)
    }

    //判断是否点击到View所在位置
    private fun isTouchPointInSendLayout(view: View?, event: MotionEvent): Boolean {
        val x = event.x
        val y = event.y
        if (view == null) {
            return false
        }
        val location = IntArray(2)
        view.getLocationOnScreen(location)
        val left = location[0]
        val top = location[1]
        val right = left + view.measuredWidth
        val bottom = top + view.measuredHeight
        return (y >= top && y <= bottom && x >= left
                && x <= right)
    }

    fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }
}